<template>
  <div
    class="upload-file-container"
    :class="{ show: type == 'show', uploadHide }"
  >
    <el-upload
      ref="upload"
      class="upload-demo"
      :headers="headers"
      :action="$store.getters.updateURL + '/attachment/uploadAndSave'"
      :on-success="handleUploadSuccess"
      :before-upload="handleBeforeUpload"
      :before-remove="handleBeforeRemove"
      :on-remove="handleRemove"
      :on-preview="handlePreview"
      :on-exceed="handleOnExceed"
      :limit="limit"
      multiple
      v-bind="$attrs"
      v-on="$listeners"
      :file-list="fileList"
      :show-file-list="showList"
    >
      <template v-if="$slots.default">
        <slot />
      </template>
      <template v-else>
        <el-button icon="el-icon-upload" size="small" type="primary">
          点击上传
        </el-button>
      </template>
    </el-upload>
    <div v-if="$slots.description" class="description">
      <slot name="description" />
    </div>
    <div v-else class="description">
      {{ description }}
    </div>
    <ElImageViewer v-if="imgShow" :on-close="handleClose" :url-list="imgUrl" />
  </div>
</template>

<script>
import { Image } from 'element-ui'
import checkSuffix from '@/utils/checkSuffix.js'
export default {
  components: {
    ElImageViewer: Image.components.ImageViewer
  },
  props: {
    uploadHide: {
      type: Boolean,
      default: false
    },
    // 文字描述
    description: {
      default: '只能上传jpg/png文件，且不超过500kb'
    },
    // 显示上传按钮
    showBtn: {
      type: Boolean,
      default: true
    },
    // 显示上传文件列表
    showList: {
      type: Boolean,
      default: true
    },
    limit: {
      type: Number
    },
    value: {
      type: Array
    },
    // 上传类型  show  为show时 禁止删除文件
    type: String
  },
  data() {
    return {
      headers: { Authorization: `Bearer ${this.$store.getters.token}` },
      imgType: 'png,jpg,jpeg,bmp,gif,webp',
      fileList: [],
      imgPreviewList: [],
      imgShow: false, // 预览图片
      imgUrl: '' // 预览图片地址
    }
  },

  watch: {
    value: {
      handler(val) {
        if (val) {
          this.initFileList(val)
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    handleClose() {
      this.imgShow = false
    },
    // 初始化文件
    initFileList(val) {
      const res = val?.map(item => {
        const isImg = checkSuffix(item.url, this.imgType)
        if (isImg) {
          this.imgPreviewList.push({
            id: item.attachment_id || item.id,
            name: item.title || item.name,
            url: item.source || item.url
          })
        }
        return {
          id: item.attachment_id || item.id,
          name: item.title || item.name,
          url: item.source || item.url
        }
      })
      if (
        res.map(item => item.id).join(',') !=
        this.fileList.map(item => item.id).join(',')
      ) {
        this.fileList = res || []
      }
    },
    // 上传成功
    handleUploadSuccess(res, file, fileList) {
      if (res.code == 0 || res.code == -200) {
        fileList.find(item => {
          if (item.uid == file.uid) {
            const { id, name, url } = item.response.data
            item.id = id
            item.name = name
            item.url = url
          }
        })

        this.fileList = fileList
        this.$emit('input', fileList)
        this.$emit('success', file, fileList)
      } else {
        const fileArr = fileList.filter(item => item.uid != file.uid)
        this.fileList = fileArr
        this.$emit('input', fileArr)
        this.$message.warning(res.msg)
      }
    },
    // 删除之前
    handleBeforeRemove() {
      if (this.type == 'show') {
        return false
      }
    },
    // 删除
    handleRemove(file) {},
    // 上传之前
    handleBeforeUpload(file) {},
    // 打开图片
    openImg(url) {
      const isHttp = url.includes(this.$store.getters.imgURL)
      this.imgShow = true
      this.imgUrl = [isHttp ? url : this.$store.getters.imgURL + url]
    },
    // 预览
    handlePreview(file) {
      const isImg = checkSuffix(file.url, this.imgType)
      if (isImg) {
        this.openImg(file.url)
      } else {
        window.open(this.$store.getters.imgURL + file.url)
      }
    },
    // 上传数量校验
    handleOnExceed() {
      if (this.limit) {
        this.$message.error(`当前限制选择 ${this.limit} 个文件`)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-file-container.show {
  ::v-deep {
    .el-icon-close,
    .el-icon-close-tip {
      display: none !important;
    }
    .el-upload-list__item-status-label {
      display: inline-block;
    }
  }
}

.upload-file-container.uploadHide {
  ::v-deep {
    .el-upload.el-upload--text {
      display: none;
    }
  }
}
</style>
